<template>
  <div data-desc="图表" class="line-chart" ref="lineChart"></div>
</template>

<script setup>
// 柱状图
import { onMounted, ref, onUnmounted, markRaw } from 'vue'

import * as echarts from 'echarts/core'
import {
  GridComponent,
  LegendComponent,
  TooltipComponent
} from 'echarts/components'

import { BarChart } from 'echarts/charts'
import { SVGRenderer } from 'echarts/renderers'

echarts.use([
  GridComponent,
  BarChart,
  SVGRenderer,
  LegendComponent,
  TooltipComponent
])

import { lineOptions, getRandomList } from './data.js'

let chartInstance = markRaw(null)

const lineChart = ref()

let option = lineOptions

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// const initEvent = () => {
// 已经使用其他方案监听了DOM变化，不需要这个了
//   window.addEventListener('resize', resizeChart, false)
// }

let m = null

const initChat = () => {
  // setTimeout(() => {
  //   console.log('echart图表初始化--前')
  //   chartInstance = echarts.init(lineChart.value)
  //   option && chartInstance.setOption(option)
  //   console.log('echart图表初始化---后')
  // }, 500);

  // 存在执行时机问题，图表先初始化了，autofit后执行，也没缩小/放大，但是图表没有重新渲染， 下面的 resizeObserver 就是重新绘制图表
  // console.log('echart图表初始化--前')
  chartInstance = echarts.init(lineChart.value)
  option && chartInstance.setOption(option)
  // console.log('echart图表初始化---后')

  // 监听根元素的改变，经过测试，发现监听图表元素存在问题, 会导致图表比计算的大，导致最外层的元素存在问题
  const body = document.querySelector('#app')

  m = new ResizeObserver(() => {
    resizeChart()
  })

  m.observe(body)

  // initEvent()
}

let timer = null

const fetchData = () => {
  const updateChart = () => {
    let { xData, yData } = getRandomList()

    chartInstance.setOption({
      xAxis: {
        data: xData
      },
      series: [
        {
          data: yData[0]
        },
        {
          data: yData[1]
        }
      ]
    })
  }

  timer = setInterval(() => {
    updateChart()
  }, 1500)
}

onMounted(() => {
  initChat()

  fetchData()
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null

    // window.removeEventListener('resize', resizeChart)
  }

  if (timer) {
    clearInterval(timer)
    timer = null
  }

  if(m) {
    m.disconnect()
  }
})
</script>

<style lang="scss" scoped>
.line-chart {
  width: 100%;
  // 375px
  height: 19.53125vw;
  // 不能使用px 在异形屏上，会出现图形溢出
  // height: 375px;
  // height: 60%;
}

</style>
